package org.zjt.agent.generate.bytebuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.pool.TypePool;
import org.zjt.agent.ClassDefineDescription;
import org.zjt.agent.Order;
import org.zjt.agent.generate.ClassHandler;
import org.zjt.agent.generate.GeneratorEnum;
import org.zjt.agent.generate.MethodRedefineStrategy;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-05 下午1:23
 * @see
 */
public class PersonClassHandler implements ClassHandler<ClassDefineDescription> {

    private TypePool typePool = TypePool.Default.ofClassPath();

    private ByteBuddy byteBuddy = new ByteBuddy();

    @Override
    public Optional<byte[]> redefine(ClassDefineDescription classDefine) {
        byte[] bytes = byteBuddy.redefine(typePool.describe(classDefine.getClassName()).resolve(), ClassFileLocator.ForClassLoader.of(classDefine.getClassLoader()))
                .defineField("qux", String.class, Visibility.PRIVATE)
                .method(ElementMatchers.named("toString"))
                .intercept(FixedValue.value("Hello World!"))
                .make()
                .getBytes();

        return Optional.of(bytes);
    }

    @Override
    public boolean support(ClassDefineDescription classDefine) {
        return Objects.equals("org.zjt.agent.domain.Person",classDefine.getClassName());
    }

    @Override
    public int order() {
        return Order.HIGH.getValue();
    }

    @Override
    public GeneratorEnum getGenerator() {
        return GeneratorEnum.BYTE_BUDDY;
    }

    @Override
    public void addMethodRedefineStrategies(List<MethodRedefineStrategy> methodRedefineStrategies) {

    }

    @Override
    public void addMethodRedefineStrategie(MethodRedefineStrategy methodRedefineStrategie) {

    }


}
